# -*- coding: utf-8 -*-

from shippingmall.items import shippingmallSku
from zc_core.model.items import Catalog, ItemData
from zc_core.util.sku_id_parser import convert_id2code
import json
import math
from zc_core.util.http_util import *
from pyquery import PyQuery
from zc_core.util.encrypt_util import md5


# 解析catalog列表
def parse_catalog(response):
    cats = list()
    json_data = json.loads(response.text)
    data = json_data['data']['product']
    jpy = PyQuery(data)
    re.findall('''this,'(.*?)',true''', data)

    for jpy1 in jpy('#cate-menu-list-item').items():
        cat1_name = jpy1('.cate-menu-list-item-wrapper span').text()
        cat1_id = md5(cat1_name + ":1")
        cat11 = _build_catalog(cat1_id, cat1_name, '', 1)
        cats.append(cat11)
        for jpy2 in jpy1('.cate-menu-list-panel-item').items():
            cat2_name = jpy2('.cate-menu-list-panel-main span').text()
            cat2_id = md5(cat2_name + ":2")
            cat22 = _build_catalog(cat2_id, cat2_name, cat1_id, 2)
            cats.append(cat22)
            for jpy3 in jpy2('.cate-menu-list-panel-vice a').items():
                cat3_id = re.search('\d+', jpy3.attr('href'))
                if cat3_id:
                    cat3_id = cat3_id.group()
                    cat3_name = jpy3.text()
                    cat33 = _build_catalog(cat3_id, cat3_name, cat2_id, 3)
                    cats.append(cat33)
    return cats


def _build_catalog(cat_id, cat_name, parent_id, level):
    cat = Catalog()
    cat['catalogId'] = cat_id
    cat['catalogName'] = cat_name
    cat['parentId'] = parent_id
    cat['level'] = level
    if level == 3:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 0

    return cat


# 维度：三级分页，解析sku列表页数
def parse_total_page(response):
    json_data = json.loads(response.text)

    return json_data['data']['totalPage']


# 维度：品牌，解析sku列表页数
def parse_brand_total_page(response):
    page_json = json.loads(response.text)
    total_page = page_json['result']['pageTotal']

    return total_page


# 解析阶梯价格页数
def parse_price_page(num, size=20):
    return math.ceil(num / size)


def parse_price_page_xx(response):
    return json.loads(response.text)['result']['totalCount']


# 解析stock
def parse_stock(response):
    if response.text and 'True' in response.text:
        return True
    return False


# 解析ItemData
def parse_item_data(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    jpy = PyQuery(response.text)
    result = ItemData()
    skuName = jpy('.productName').text().replace(' ', '').replace('\n举报', '')
    skuId = re.search('\d+', response.url).group()
    print(response.url, jpy('.market_price').text())
    originPrice = float(jpy('.market_price').text())
    salePrice = float(re.search('\d+', jpy('.price').text()).group())
    soldCount = int(re.search('\d+',
                              [i.text() for i in jpy('.reference').items()][-1].replace(' ', '').replace('已购人数',
                                                                                                         '')).group())
    img_url = [i.attr('src') for i in jpy('.box-lun li img').items()][0]
    result['salePrice'] = salePrice
    result['skuId'] = skuId
    # 商品原价
    result['originPrice'] = originPrice
    result['skuName'] = skuName
    result['batchNo'] = batch_no
    # 主图列表
    result['skuImg'] = img_url
    result['soldCount'] = soldCount
    result['catalog2Name'] = [i.text() for i in jpy('.crumbs span').items()][1]
    result['catalog2Id'] = [i.attr('data-cid') for i in jpy('.crumbs span').items()][1]
    return result


if __name__ == '__main__':
    pass
